3 * Cache of the contents of localisation files.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
23 use CLDRPluralRuleParser\Evaluator
;
24 use CLDRPluralRuleParser\Error
as CLDRPluralRuleError
;
25 use MediaWiki\Logger\LoggerFactory
;
26 use MediaWiki\MediaWikiServices
;
29 * Class for caching the contents of localisation files, Messages*.php
32 * An instance of this class is available using Language::getLocalisationCache().
34 * The values retrieved from here are merged, containing items from extension
35 * files, core messages files and the language fallback sequence (e.g. zh-cn ->
36 * zh-hans -> en ). Some common errors are corrected, for example namespace
37 * names with spaces instead of underscores, but heavyweight processing, such
38 * as grammatical transformation, is done by the caller.
40 class LocalisationCache
{
43 /** Configuration associative array */
47 * True if recaching should only be done on an explicit call to recache().
48 * Setting this reduces the overhead of cache freshness checking, which
49 * requires doing a stat() for every extension i18n file.
51 private $manualRecache = false;
54 * True to treat all files as expired until they are regenerated by this object.
56 private $forceRecache = false;
59 * The cache data. 3-d array, where the first key is the language code,
60 * the second key is the item key e.g. 'messages', and the third key is
61 * an item specific subkey index. Some items are not arrays and so for those
62 * items, there are no subkeys.
67 * The persistent store object. An instance of LCStore.
74 * @var \Psr\Log\LoggerInterface
79 * A 2-d associative array, code/key, where presence indicates that the item
80 * is loaded. Value arbitrary.
82 * For split items, if set, this indicates that all of the subitems have been
85 private $loadedItems = [];
88 * A 3-d associative array, code/key/subkey, where presence indicates that
89 * the subitem is loaded. Only used for the split items, i.e. messages.
91 private $loadedSubitems = [];
94 * An array where presence of a key indicates that that language has been
95 * initialised. Initialisation includes checking for cache expiry and doing
96 * any necessary updates.
98 private $initialisedLangs = [];
101 * An array mapping non-existent pseudo-languages to fallback languages. This
102 * is filled by initShallowFallback() when data is requested from a language
103 * that lacks a Messages*.php file.
105 private $shallowFallbacks = [];
108 * An array where the keys are codes that have been recached by this instance.
110 private $recachedLangs = [];
115 public static $allKeys = [
116 'fallback', 'namespaceNames', 'bookstoreList',
117 'magicWords', 'messages', 'rtl', 'capitalizeAllNouns',
118 'digitTransformTable', 'separatorTransformTable',
119 'minimumGroupingDigits', 'fallback8bitEncoding',
120 'linkPrefixExtension', 'linkTrail', 'linkPrefixCharset',
121 'namespaceAliases', 'dateFormats', 'datePreferences',
122 'datePreferenceMigrationMap', 'defaultDateFormat',
123 'specialPageAliases', 'imageFiles', 'preloadedMessages',
124 'namespaceGenderAliases', 'digitGroupingPattern', 'pluralRules',
125 'pluralRuleTypes', 'compiledPluralRules',
129 * Keys for items which consist of associative arrays, which may be merged
130 * by a fallback sequence.
132 public static $mergeableMapKeys = [ 'messages', 'namespaceNames',
133 'namespaceAliases', 'dateFormats', 'imageFiles', 'preloadedMessages'
137 * Keys for items which are a numbered array.
139 public static $mergeableListKeys = [];
142 * Keys for items which contain an array of arrays of equivalent aliases
143 * for each subitem. The aliases may be merged by a fallback sequence.
145 public static $mergeableAliasListKeys = [ 'specialPageAliases' ];
148 * Keys for items which contain an associative array, and may be merged if
149 * the primary value contains the special array key "inherit". That array
150 * key is removed after the first merge.
152 public static $optionalMergeKeys = [ 'bookstoreList' ];
155 * Keys for items that are formatted like $magicWords
157 public static $magicWordKeys = [ 'magicWords' ];
160 * Keys for items where the subitems are stored in the backend separately.
162 public static $splitKeys = [ 'messages' ];
165 * Keys which are loaded automatically by initLanguage()
167 public static $preloadedKeys = [ 'dateFormats', 'namespaceNames' ];
170 * Associative array of cached plural rules. The key is the language code,
171 * the value is an array of plural rules for that language.
173 private $pluralRules = null;
176 * Associative array of cached plural rule types. The key is the language
177 * code, the value is an array of plural rule types for that language. For
178 * example, $pluralRuleTypes['ar'] = ['zero', 'one', 'two', 'few', 'many'].
179 * The index for each rule type matches the index for the rule in
180 * $pluralRules, thus allowing correlation between the two. The reason we
181 * don't just use the type names as the keys in $pluralRules is because
182 * Language::convertPlural applies the rules based on numeric order (or
183 * explicit numeric parameter), not based on the name of the rule type. For
184 * example, {{plural:count|wordform1|wordform2|wordform3}}, rather than
185 * {{plural:count|one=wordform1|two=wordform2|many=wordform3}}.
187 private $pluralRuleTypes = null;
189 private $mergeableKeys = null;
192 * For constructor parameters, see the documentation in DefaultSettings.php
193 * for $wgLocalisationCacheConf.
196 * @throws MWException
198 function __construct( $conf ) {
199 global $wgCacheDirectory;
202 $this->logger
= LoggerFactory
::getInstance( 'localisation' );
204 $directory = !empty( $conf['storeDirectory'] ) ?
$conf['storeDirectory'] : $wgCacheDirectory;
206 $storeArg['directory'] = $directory;
208 if ( !empty( $conf['storeClass'] ) ) {
209 $storeClass = $conf['storeClass'];
211 switch ( $conf['store'] ) {
214 $storeClass = LCStoreCDB
::class;
217 $storeClass = LCStoreDB
::class;
218 $storeArg['server'] = $conf['storeServer'] ??
[];
221 $storeClass = LCStoreStaticArray
::class;
225 $storeClass = LCStoreCDB
::class;
227 $storeClass = LCStoreDB
::class;
228 $storeArg['server'] = $conf['storeServer'] ??
[];
232 throw new MWException(
233 'Please set $wgLocalisationCacheConf[\'store\'] to something sensible.'
237 $this->logger
->debug( static::class . ": using store $storeClass" );
239 $this->store
= new $storeClass( $storeArg );
240 foreach ( [ 'manualRecache', 'forceRecache' ] as $var ) {
241 if ( isset( $conf[$var] ) ) {
242 $this->$var = $conf[$var];
248 * Returns true if the given key is mergeable, that is, if it is an associative
249 * array which can be merged through a fallback sequence.
253 public function isMergeableKey( $key ) {
254 if ( $this->mergeableKeys
=== null ) {
255 $this->mergeableKeys
= array_flip( array_merge(
256 self
::$mergeableMapKeys,
257 self
::$mergeableListKeys,
258 self
::$mergeableAliasListKeys,
259 self
::$optionalMergeKeys,
264 return isset( $this->mergeableKeys
[$key] );
270 * Warning: this may be slow for split items (messages), since it will
271 * need to fetch all of the subitems from the cache individually.
272 * @param string $code
276 public function getItem( $code, $key ) {
277 if ( !isset( $this->loadedItems
[$code][$key] ) ) {
278 $this->loadItem( $code, $key );
281 if ( $key === 'fallback' && isset( $this->shallowFallbacks
[$code] ) ) {
282 return $this->shallowFallbacks
[$code];
285 return $this->data
[$code][$key];
289 * Get a subitem, for instance a single message for a given language.
290 * @param string $code
292 * @param string $subkey
295 public function getSubitem( $code, $key, $subkey ) {
296 if ( !isset( $this->loadedSubitems
[$code][$key][$subkey] ) &&
297 !isset( $this->loadedItems
[$code][$key] )
299 $this->loadSubitem( $code, $key, $subkey );
302 return $this->data
[$code][$key][$subkey] ??
null;
306 * Get the list of subitem keys for a given item.
308 * This is faster than array_keys($lc->getItem(...)) for the items listed in
311 * Will return null if the item is not found, or false if the item is not an
313 * @param string $code
315 * @return bool|null|string|string[]
317 public function getSubitemList( $code, $key ) {
318 if ( in_array( $key, self
::$splitKeys ) ) {
319 return $this->getSubitem( $code, 'list', $key );
321 $item = $this->getItem( $code, $key );
322 if ( is_array( $item ) ) {
323 return array_keys( $item );
331 * Load an item into the cache.
332 * @param string $code
335 protected function loadItem( $code, $key ) {
336 if ( !isset( $this->initialisedLangs
[$code] ) ) {
337 $this->initLanguage( $code );
340 // Check to see if initLanguage() loaded it for us
341 if ( isset( $this->loadedItems
[$code][$key] ) ) {
345 if ( isset( $this->shallowFallbacks
[$code] ) ) {
346 $this->loadItem( $this->shallowFallbacks
[$code], $key );
351 if ( in_array( $key, self
::$splitKeys ) ) {
352 $subkeyList = $this->getSubitem( $code, 'list', $key );
353 foreach ( $subkeyList as $subkey ) {
354 if ( isset( $this->data
[$code][$key][$subkey] ) ) {
357 $this->data
[$code][$key][$subkey] = $this->getSubitem( $code, $key, $subkey );
360 $this->data
[$code][$key] = $this->store
->get( $code, $key );
363 $this->loadedItems
[$code][$key] = true;
367 * Load a subitem into the cache
368 * @param string $code
370 * @param string $subkey
372 protected function loadSubitem( $code, $key, $subkey ) {
373 if ( !in_array( $key, self
::$splitKeys ) ) {
374 $this->loadItem( $code, $key );
379 if ( !isset( $this->initialisedLangs
[$code] ) ) {
380 $this->initLanguage( $code );
383 // Check to see if initLanguage() loaded it for us
384 if ( isset( $this->loadedItems
[$code][$key] ) ||
385 isset( $this->loadedSubitems
[$code][$key][$subkey] )
390 if ( isset( $this->shallowFallbacks
[$code] ) ) {
391 $this->loadSubitem( $this->shallowFallbacks
[$code], $key, $subkey );
396 $value = $this->store
->get( $code, "$key:$subkey" );
397 $this->data
[$code][$key][$subkey] = $value;
398 $this->loadedSubitems
[$code][$key][$subkey] = true;
402 * Returns true if the cache identified by $code is missing or expired.
404 * @param string $code
408 public function isExpired( $code ) {
409 if ( $this->forceRecache
&& !isset( $this->recachedLangs
[$code] ) ) {
410 $this->logger
->debug( __METHOD__
. "($code): forced reload\n" );
415 $deps = $this->store
->get( $code, 'deps' );
416 $keys = $this->store
->get( $code, 'list' );
417 $preload = $this->store
->get( $code, 'preload' );
418 // Different keys may expire separately for some stores
419 if ( $deps === null ||
$keys === null ||
$preload === null ) {
420 $this->logger
->debug( __METHOD__
. "($code): cache missing, need to make one\n" );
425 foreach ( $deps as $dep ) {
426 // Because we're unserializing stuff from cache, we
427 // could receive objects of classes that don't exist
428 // anymore (e.g. uninstalled extensions)
429 // When this happens, always expire the cache
430 if ( !$dep instanceof CacheDependency ||
$dep->isExpired() ) {
431 $this->logger
->debug( __METHOD__
. "($code): cache for $code expired due to " .
432 get_class( $dep ) . "\n" );
442 * Initialise a language in this object. Rebuild the cache if necessary.
443 * @param string $code
444 * @throws MWException
446 protected function initLanguage( $code ) {
447 if ( isset( $this->initialisedLangs
[$code] ) ) {
451 $this->initialisedLangs
[$code] = true;
453 # If the code is of the wrong form for a Messages*.php file, do a shallow fallback
454 if ( !Language
::isValidBuiltInCode( $code ) ) {
455 $this->initShallowFallback( $code, 'en' );
460 # Recache the data if necessary
461 if ( !$this->manualRecache
&& $this->isExpired( $code ) ) {
462 if ( Language
::isSupportedLanguage( $code ) ) {
463 $this->recache( $code );
464 } elseif ( $code === 'en' ) {
465 throw new MWException( 'MessagesEn.php is missing.' );
467 $this->initShallowFallback( $code, 'en' );
474 $preload = $this->getItem( $code, 'preload' );
475 if ( $preload === null ) {
476 if ( $this->manualRecache
) {
477 // No Messages*.php file. Do shallow fallback to en.
478 if ( $code === 'en' ) {
479 throw new MWException( 'No localisation cache found for English. ' .
480 'Please run maintenance/rebuildLocalisationCache.php.' );
482 $this->initShallowFallback( $code, 'en' );
486 throw new MWException( 'Invalid or missing localisation cache.' );
489 $this->data
[$code] = $preload;
490 foreach ( $preload as $key => $item ) {
491 if ( in_array( $key, self
::$splitKeys ) ) {
492 foreach ( $item as $subkey => $subitem ) {
493 $this->loadedSubitems
[$code][$key][$subkey] = true;
496 $this->loadedItems
[$code][$key] = true;
502 * Create a fallback from one language to another, without creating a
503 * complete persistent cache.
504 * @param string $primaryCode
505 * @param string $fallbackCode
507 public function initShallowFallback( $primaryCode, $fallbackCode ) {
508 $this->data
[$primaryCode] =& $this->data
[$fallbackCode];
509 $this->loadedItems
[$primaryCode] =& $this->loadedItems
[$fallbackCode];
510 $this->loadedSubitems
[$primaryCode] =& $this->loadedSubitems
[$fallbackCode];
511 $this->shallowFallbacks
[$primaryCode] = $fallbackCode;
515 * Read a PHP file containing localisation data.
516 * @param string $_fileName
517 * @param string $_fileType
518 * @throws MWException
521 protected function readPHPFile( $_fileName, $_fileType ) {
522 // Disable APC caching
523 Wikimedia\
suppressWarnings();
524 $_apcEnabled = ini_set( 'apc.cache_by_default', '0' );
525 Wikimedia\restoreWarnings
();
529 Wikimedia\
suppressWarnings();
530 ini_set( 'apc.cache_by_default', $_apcEnabled );
531 Wikimedia\restoreWarnings
();
534 if ( $_fileType == 'core' ||
$_fileType == 'extension' ) {
535 foreach ( self
::$allKeys as $key ) {
536 // Not all keys are set in language files, so
537 // check they exist first
538 if ( isset( $
$key ) ) {
542 } elseif ( $_fileType == 'aliases' ) {
543 if ( isset( $aliases ) ) {
544 $data['aliases'] = $aliases;
547 throw new MWException( __METHOD__
. ": Invalid file type: $_fileType" );
554 * Read a JSON file containing localisation messages.
555 * @param string $fileName Name of file to read
556 * @throws MWException If there is a syntax error in the JSON file
557 * @return array Array with a 'messages' key, or empty array if the file doesn't exist
559 public function readJSONFile( $fileName ) {
560 if ( !is_readable( $fileName ) ) {
564 $json = file_get_contents( $fileName );
565 if ( $json === false ) {
569 $data = FormatJson
::decode( $json, true );
570 if ( $data === null ) {
571 throw new MWException( __METHOD__
. ": Invalid JSON file: $fileName" );
574 // Remove keys starting with '@', they're reserved for metadata and non-message data
575 foreach ( $data as $key => $unused ) {
576 if ( $key === '' ||
$key[0] === '@' ) {
577 unset( $data[$key] );
581 // The JSON format only supports messages, none of the other variables, so wrap the data
582 return [ 'messages' => $data ];
586 * Get the compiled plural rules for a given language from the XML files.
588 * @param string $code
591 public function getCompiledPluralRules( $code ) {
592 $rules = $this->getPluralRules( $code );
593 if ( $rules === null ) {
597 $compiledRules = Evaluator
::compile( $rules );
598 } catch ( CLDRPluralRuleError
$e ) {
599 $this->logger
->debug( $e->getMessage() );
604 return $compiledRules;
608 * Get the plural rules for a given language from the XML files.
611 * @param string $code
614 public function getPluralRules( $code ) {
615 if ( $this->pluralRules
=== null ) {
616 $this->loadPluralFiles();
618 return $this->pluralRules
[$code] ??
null;
622 * Get the plural rule types for a given language from the XML files.
625 * @param string $code
628 public function getPluralRuleTypes( $code ) {
629 if ( $this->pluralRuleTypes
=== null ) {
630 $this->loadPluralFiles();
632 return $this->pluralRuleTypes
[$code] ??
null;
636 * Load the plural XML files.
638 protected function loadPluralFiles() {
640 $cldrPlural = "$IP/languages/data/plurals.xml";
641 $mwPlural = "$IP/languages/data/plurals-mediawiki.xml";
642 // Load CLDR plural rules
643 $this->loadPluralFile( $cldrPlural );
644 if ( file_exists( $mwPlural ) ) {
645 // Override or extend
646 $this->loadPluralFile( $mwPlural );
651 * Load a plural XML file with the given filename, compile the relevant
652 * rules, and save the compiled rules in a process-local cache.
654 * @param string $fileName
655 * @throws MWException
657 protected function loadPluralFile( $fileName ) {
658 // Use file_get_contents instead of DOMDocument::load (T58439)
659 $xml = file_get_contents( $fileName );
661 throw new MWException( "Unable to read plurals file $fileName" );
663 $doc = new DOMDocument
;
664 $doc->loadXML( $xml );
665 $rulesets = $doc->getElementsByTagName( "pluralRules" );
666 foreach ( $rulesets as $ruleset ) {
667 $codes = $ruleset->getAttribute( 'locales' );
670 $ruleElements = $ruleset->getElementsByTagName( "pluralRule" );
671 foreach ( $ruleElements as $elt ) {
672 $ruleType = $elt->getAttribute( 'count' );
673 if ( $ruleType === 'other' ) {
674 // Don't record "other" rules, which have an empty condition
677 $rules[] = $elt->nodeValue
;
678 $ruleTypes[] = $ruleType;
680 foreach ( explode( ' ', $codes ) as $code ) {
681 $this->pluralRules
[$code] = $rules;
682 $this->pluralRuleTypes
[$code] = $ruleTypes;
688 * Read the data from the source files for a given language, and register
689 * the relevant dependencies in the $deps array. If the localisation
690 * exists, the data array is returned, otherwise false is returned.
692 * @param string $code
693 * @param array &$deps
696 protected function readSourceFilesAndRegisterDeps( $code, &$deps ) {
699 // This reads in the PHP i18n file with non-messages l10n data
700 $fileName = Language
::getMessagesFileName( $code );
701 if ( !file_exists( $fileName ) ) {
704 $deps[] = new FileDependency( $fileName );
705 $data = $this->readPHPFile( $fileName, 'core' );
708 # Load CLDR plural rules for JavaScript
709 $data['pluralRules'] = $this->getPluralRules( $code );
711 $data['compiledPluralRules'] = $this->getCompiledPluralRules( $code );
712 # Load plural rule types
713 $data['pluralRuleTypes'] = $this->getPluralRuleTypes( $code );
715 $deps['plurals'] = new FileDependency( "$IP/languages/data/plurals.xml" );
716 $deps['plurals-mw'] = new FileDependency( "$IP/languages/data/plurals-mediawiki.xml" );
722 * Merge two localisation values, a primary and a fallback, overwriting the
723 * primary value in place.
725 * @param mixed &$value
726 * @param mixed $fallbackValue
728 protected function mergeItem( $key, &$value, $fallbackValue ) {
729 if ( !is_null( $value ) ) {
730 if ( !is_null( $fallbackValue ) ) {
731 if ( in_array( $key, self
::$mergeableMapKeys ) ) {
732 $value = $value +
$fallbackValue;
733 } elseif ( in_array( $key, self
::$mergeableListKeys ) ) {
734 $value = array_unique( array_merge( $fallbackValue, $value ) );
735 } elseif ( in_array( $key, self
::$mergeableAliasListKeys ) ) {
736 $value = array_merge_recursive( $value, $fallbackValue );
737 } elseif ( in_array( $key, self
::$optionalMergeKeys ) ) {
738 if ( !empty( $value['inherit'] ) ) {
739 $value = array_merge( $fallbackValue, $value );
742 if ( isset( $value['inherit'] ) ) {
743 unset( $value['inherit'] );
745 } elseif ( in_array( $key, self
::$magicWordKeys ) ) {
746 $this->mergeMagicWords( $value, $fallbackValue );
750 $value = $fallbackValue;
755 * @param mixed &$value
756 * @param mixed $fallbackValue
758 protected function mergeMagicWords( &$value, $fallbackValue ) {
759 foreach ( $fallbackValue as $magicName => $fallbackInfo ) {
760 if ( !isset( $value[$magicName] ) ) {
761 $value[$magicName] = $fallbackInfo;
763 $oldSynonyms = array_slice( $fallbackInfo, 1 );
764 $newSynonyms = array_slice( $value[$magicName], 1 );
765 $synonyms = array_values( array_unique( array_merge(
766 $newSynonyms, $oldSynonyms ) ) );
767 $value[$magicName] = array_merge( [ $fallbackInfo[0] ], $synonyms );
773 * Given an array mapping language code to localisation value, such as is
774 * found in extension *.i18n.php files, iterate through a fallback sequence
775 * to merge the given data with an existing primary value.
777 * Returns true if any data from the extension array was used, false
779 * @param array $codeSequence
781 * @param mixed &$value
782 * @param mixed $fallbackValue
785 protected function mergeExtensionItem( $codeSequence, $key, &$value, $fallbackValue ) {
787 foreach ( $codeSequence as $code ) {
788 if ( isset( $fallbackValue[$code] ) ) {
789 $this->mergeItem( $key, $value, $fallbackValue[$code] );
798 * Gets the combined list of messages dirs from
799 * core and extensions
804 public function getMessagesDirs() {
807 $config = MediaWikiServices
::getInstance()->getMainConfig();
808 $messagesDirs = $config->get( 'MessagesDirs' );
810 'core' => "$IP/languages/i18n",
811 'exif' => "$IP/languages/i18n/exif",
812 'api' => "$IP/includes/api/i18n",
813 'oojs-ui' => "$IP/resources/lib/ooui/i18n",
818 * Load localisation data for a given language for both core and extensions
819 * and save it to the persistent cache store and the process cache
820 * @param string $code
821 * @throws MWException
823 public function recache( $code ) {
824 global $wgExtensionMessagesFiles;
827 throw new MWException( "Invalid language code requested" );
829 $this->recachedLangs
[$code] = true;
832 $initialData = array_fill_keys( self
::$allKeys, null );
833 $coreData = $initialData;
836 # Load the primary localisation from the source file
837 $data = $this->readSourceFilesAndRegisterDeps( $code, $deps );
838 if ( $data === false ) {
839 $this->logger
->debug( __METHOD__
. ": no localisation file for $code, using fallback to en\n" );
840 $coreData['fallback'] = 'en';
842 $this->logger
->debug( __METHOD__
. ": got localisation for $code from source\n" );
844 # Merge primary localisation
845 foreach ( $data as $key => $value ) {
846 $this->mergeItem( $key, $coreData[$key], $value );
850 # Fill in the fallback if it's not there already
851 if ( ( is_null( $coreData['fallback'] ) ||
$coreData['fallback'] === false ) && $code === 'en' ) {
852 $coreData['fallback'] = false;
853 $coreData['originalFallbackSequence'] = $coreData['fallbackSequence'] = [];
855 if ( !is_null( $coreData['fallback'] ) ) {
856 $coreData['fallbackSequence'] = array_map( 'trim', explode( ',', $coreData['fallback'] ) );
858 $coreData['fallbackSequence'] = [];
860 $len = count( $coreData['fallbackSequence'] );
862 # Before we add the 'en' fallback for messages, keep a copy of
863 # the original fallback sequence
864 $coreData['originalFallbackSequence'] = $coreData['fallbackSequence'];
866 # Ensure that the sequence ends at 'en' for messages
867 if ( !$len ||
$coreData['fallbackSequence'][$len - 1] !== 'en' ) {
868 $coreData['fallbackSequence'][] = 'en';
872 $codeSequence = array_merge( [ $code ], $coreData['fallbackSequence'] );
873 $messageDirs = $this->getMessagesDirs();
875 # Load non-JSON localisation data for extensions
876 $extensionData = array_fill_keys( $codeSequence, $initialData );
877 foreach ( $wgExtensionMessagesFiles as $extension => $fileName ) {
878 if ( isset( $messageDirs[$extension] ) ) {
879 # This extension has JSON message data; skip the PHP shim
883 $data = $this->readPHPFile( $fileName, 'extension' );
886 foreach ( $data as $key => $item ) {
887 foreach ( $codeSequence as $csCode ) {
888 if ( isset( $item[$csCode] ) ) {
889 $this->mergeItem( $key, $extensionData[$csCode][$key], $item[$csCode] );
896 $deps[] = new FileDependency( $fileName );
900 # Load the localisation data for each fallback, then merge it into the full array
901 $allData = $initialData;
902 foreach ( $codeSequence as $csCode ) {
903 $csData = $initialData;
905 # Load core messages and the extension localisations.
906 foreach ( $messageDirs as $dirs ) {
907 foreach ( (array)$dirs as $dir ) {
908 $fileName = "$dir/$csCode.json";
909 $data = $this->readJSONFile( $fileName );
911 foreach ( $data as $key => $item ) {
912 $this->mergeItem( $key, $csData[$key], $item );
915 $deps[] = new FileDependency( $fileName );
919 # Merge non-JSON extension data
920 if ( isset( $extensionData[$csCode] ) ) {
921 foreach ( $extensionData[$csCode] as $key => $item ) {
922 $this->mergeItem( $key, $csData[$key], $item );
926 if ( $csCode === $code ) {
927 # Merge core data into extension data
928 foreach ( $coreData as $key => $item ) {
929 $this->mergeItem( $key, $csData[$key], $item );
932 # Load the secondary localisation from the source file to
933 # avoid infinite cycles on cyclic fallbacks
934 $fbData = $this->readSourceFilesAndRegisterDeps( $csCode, $deps );
935 if ( $fbData !== false ) {
936 # Only merge the keys that make sense to merge
937 foreach ( self
::$allKeys as $key ) {
938 if ( !isset( $fbData[$key] ) ) {
942 if ( is_null( $coreData[$key] ) ||
$this->isMergeableKey( $key ) ) {
943 $this->mergeItem( $key, $csData[$key], $fbData[$key] );
949 # Allow extensions an opportunity to adjust the data for this
951 Hooks
::run( 'LocalisationCacheRecacheFallback', [ $this, $csCode, &$csData ] );
953 # Merge the data for this fallback into the final array
954 if ( $csCode === $code ) {
957 foreach ( self
::$allKeys as $key ) {
958 if ( !isset( $csData[$key] ) ) {
962 if ( is_null( $allData[$key] ) ||
$this->isMergeableKey( $key ) ) {
963 $this->mergeItem( $key, $allData[$key], $csData[$key] );
969 # Add cache dependencies for any referenced globals
970 $deps['wgExtensionMessagesFiles'] = new GlobalDependency( 'wgExtensionMessagesFiles' );
971 // The 'MessagesDirs' config setting is used in LocalisationCache::getMessagesDirs().
972 // We use the key 'wgMessagesDirs' for historical reasons.
973 $deps['wgMessagesDirs'] = new MainConfigDependency( 'MessagesDirs' );
974 $deps['version'] = new ConstantDependency( 'LocalisationCache::VERSION' );
976 # Add dependencies to the cache entry
977 $allData['deps'] = $deps;
979 # Replace spaces with underscores in namespace names
980 $allData['namespaceNames'] = str_replace( ' ', '_', $allData['namespaceNames'] );
982 # And do the same for special page aliases. $page is an array.
983 foreach ( $allData['specialPageAliases'] as &$page ) {
984 $page = str_replace( ' ', '_', $page );
986 # Decouple the reference to prevent accidental damage
989 # If there were no plural rules, return an empty array
990 if ( $allData['pluralRules'] === null ) {
991 $allData['pluralRules'] = [];
993 if ( $allData['compiledPluralRules'] === null ) {
994 $allData['compiledPluralRules'] = [];
996 # If there were no plural rule types, return an empty array
997 if ( $allData['pluralRuleTypes'] === null ) {
998 $allData['pluralRuleTypes'] = [];
1002 $allData['list'] = [];
1003 foreach ( self
::$splitKeys as $key ) {
1004 $allData['list'][$key] = array_keys( $allData[$key] );
1007 $unused = true; // Used to be $purgeBlobs, removed in 1.34
1008 Hooks
::run( 'LocalisationCacheRecache', [ $this, $code, &$allData, &$unused ] );
1010 if ( is_null( $allData['namespaceNames'] ) ) {
1011 throw new MWException( __METHOD__
. ': Localisation data failed sanity check! ' .
1012 'Check that your languages/messages/MessagesEn.php file is intact.' );
1015 # Set the preload key
1016 $allData['preload'] = $this->buildPreload( $allData );
1018 # Save to the process cache and register the items loaded
1019 $this->data
[$code] = $allData;
1020 foreach ( $allData as $key => $item ) {
1021 $this->loadedItems
[$code][$key] = true;
1024 # Save to the persistent cache
1025 $this->store
->startWrite( $code );
1026 foreach ( $allData as $key => $value ) {
1027 if ( in_array( $key, self
::$splitKeys ) ) {
1028 foreach ( $value as $subkey => $subvalue ) {
1029 $this->store
->set( "$key:$subkey", $subvalue );
1032 $this->store
->set( $key, $value );
1035 $this->store
->finishWrite();
1037 # Clear out the MessageBlobStore
1038 # HACK: If using a null (i.e. disabled) storage backend, we
1039 # can't write to the MessageBlobStore either
1040 if ( !$this->store
instanceof LCStoreNull
) {
1041 $blobStore = MediaWikiServices
::getInstance()->getResourceLoader()->getMessageBlobStore();
1042 $blobStore->clear();
1047 * Build the preload item from the given pre-cache data.
1049 * The preload item will be loaded automatically, improving performance
1050 * for the commonly-requested items it contains.
1051 * @param array $data
1054 protected function buildPreload( $data ) {
1055 $preload = [ 'messages' => [] ];
1056 foreach ( self
::$preloadedKeys as $key ) {
1057 $preload[$key] = $data[$key];
1060 foreach ( $data['preloadedMessages'] as $subkey ) {
1061 $subitem = $data['messages'][$subkey] ??
null;
1062 $preload['messages'][$subkey] = $subitem;
1069 * Unload the data for a given language from the object cache.
1070 * Reduces memory usage.
1071 * @param string $code
1073 public function unload( $code ) {
1074 unset( $this->data
[$code] );
1075 unset( $this->loadedItems
[$code] );
1076 unset( $this->loadedSubitems
[$code] );
1077 unset( $this->initialisedLangs
[$code] );
1078 unset( $this->shallowFallbacks
[$code] );
1080 foreach ( $this->shallowFallbacks
as $shallowCode => $fbCode ) {
1081 if ( $fbCode === $code ) {
1082 $this->unload( $shallowCode );
1090 public function unloadAll() {
1091 foreach ( $this->initialisedLangs
as $lang => $unused ) {
1092 $this->unload( $lang );
1097 * Disable the storage backend
1099 public function disableBackend() {
1100 $this->store
= new LCStoreNull
;
1101 $this->manualRecache
= false;